
#include <stdint.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "ADC.h"
#include "RTC.h"
#include "LCD_functions.h"
#include "AVRBFLY.h"

uint32_t  global_seconds = 0;
uint32_t  seconds = 0;
uint32_t interval_desired;
uint8_t h,m, logstart;

/******************************************************************************
*
*   Function name:  RTC_init
*
*   returns:        none
*
*   parameters:     none
*
*   Purpose:        Start Timer/Counter2 in asynchronous operation using a
*                   32.768kHz crystal.
*
*******************************************************************************/
void RTC_init(void)
{
    cli(); // disable global interrupt
    cbiBF(TIMSK2, TOIE2);             // disable OCIE2A and TOIE2
    //TIMSK2 &= 0xfc; 
	ASSR = (1<<AS2);        // select asynchronous operation of Timer2
    TCNT2 = 0;              // clear TCNT2A
    TCCR2A |= (1<<CS22) | (1<<CS20);             // select prescaler: 32.768 kHz / 128 = 1 sec between each overflow
	while((ASSR & 0x01) | (ASSR & 0x04));       // wait for TCN2UB and TCR2UB to be cleared
    TIFR2 = 0xFF;           // clear interrupt-flags
    sbiBF(TIMSK2, TOIE2);     // enable Timer2 overflow interrupt
    //TIMSK2 |= 0x03;
	sei(); // enable_interrupt();                
    global_seconds  = 0;
	seconds = 0;
	interval_desired = Calculate_time(h,m); 
 }   

/******************************************************************************
*
*   Timer/Counter2 Overflow Interrupt Routine
*
*   Purpose: Increment the real-time clock
*            The interrupt occurs once a second (running from the 32kHz crystal)
*
*******************************************************************************/

ISR(TIMER2_OVF_vect)
{
	global_seconds++; 
	seconds++;
	uint16_t adc_output = LightIntensityCalculation(); 
	if(adc_output == 750 )    
	{if(seconds == interval_desired && logstart == 1)
	{
		//LCD_puts("MISHAAL", 1);
		LCD_Clear();
		TempCalculation(global_seconds);
		
		seconds = 0;
	}
	}
}


uint32_t Calculate_time(uint8_t hour,uint8_t minute)
{
	return (minute*60+hour*60*60);
}
